# -*- coding: utf-8 -*-
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QDialog, QMessageBox

from compoments.editWorkFillDialog import Ui_Dialog
from util import stringUtil, configJsonUtil


class EditWorkFillDialogImpl(QDialog, Ui_Dialog):
    refresh_program_signal = pyqtSignal()

    def __init__(self, parent=None, uid=None):
        super().__init__(parent)
        self.parent = parent
        self.setupUi(self)
        self.uid = uid
        self.config = configJsonUtil.get_config()
        for p in self.config['programs']:
            if str(p['id']) == uid:
                self.data = p
                break
        if self.uid is None:
            # 新增
            self.setWindowTitle('新增项目')
            self.gsLineEdit.setText("8")
            self.weightLineEdit.setText("1")
        else:
            self.setWindowTitle("修改项目")
            self.xmbhLineEdit.setText(self.data['xmbh'])
            self.xmmcLineEdit.setText(self.data['xmmc'])
            self.rwbhLineEdit.setText(self.data['rwbh'])
            self.rwmcLineEdit.setText(self.data['rwmc'])
            self.gsLineEdit.setText(str(self.data['gs']))
            self.nrLineEdit.setText(self.data['nr'])
            self.weightLineEdit.setText(str(self.data['weight']))

        self.pushButton_close.clicked.connect(self.close)
        self.pushButton_save.clicked.connect(self.save_program)
        self.show()

    def save_program(self):
        self.data = self.get_data()
        if self.uid is None:
            self.config['programs'].append(self.data)
        else:
            index = 0
            for p in self.config['programs']:
                if str(p['id']) == self.data["id"]:
                    self.config['programs'][index] = self.data
                    break
                index = index + 1
        configJsonUtil.save_json(self.config)
        self.parent.program_changed_signal.emit()
        self.close()

    def get_data(self):
        data = {'xmbh': self.xmbhLineEdit.text(), 'xmmc': self.xmmcLineEdit.text(), 'rwbh': self.rwbhLineEdit.text(),
                'rwmc': self.rwmcLineEdit.text(), 'gs': self.gsLineEdit.text(), 'nr': self.nrLineEdit.text(),
                'weight': self.weightLineEdit.text()}
        for d in data:
            if data[d] is None or data[d] == '':
                QMessageBox.warning(self, "提示", self.config['programsMap'][d] + '不能为空', QMessageBox.Yes,
                                    QMessageBox.Yes)
                return
        if self.uid is None:
            data["id"] = stringUtil.uid()
        else:
            data["id"] = self.uid
        return data
